﻿#if UNITY_EDITOR
using System;
using System.IO;
using UnityEditor;

namespace UFrame
{
    public static class JenkinsTool
    {
        public static string locationPathName = @"c:\UnityBuild\panzi.exe";
        public static BuildTarget buildTarget = BuildTarget.StandaloneWindows;
        public static BuildTargetGroup targetGroup = BuildTargetGroup.Standalone;
        public static string symbols = string.Empty;

        [MenuItem("Plateface/Jenkins/build Game", false, 1)]
        public static void BuildGame()
        {
            SetArgs();
            BuildPlayerOptions b = new BuildPlayerOptions();
            b.locationPathName = locationPathName;
            b.options = BuildOptions.None;
            b.target = buildTarget;
            b.targetGroup = targetGroup;
            BuildPipeline.BuildPlayer(b);
        }

        [MenuItem("Plateface/Jenkins/build Game AB", false, 1)]
        public static void BuildGameAB()
        {
            SetArgs();
            ABTools.BuildAB();
        }

        [MenuItem("Plateface/Jenkins/TestArgBuildGame", false, 1)]
        public static void TestArgBuildGame()
        {
            SetArgs();
        }

        public static void SetArgs()
        {
            string[] comLine = Environment.GetCommandLineArgs();
            foreach (string argLine in comLine)
            {
                if (argLine.StartsWith("args:") == false)
                {
                    continue;
                }

                string newArgLine = argLine.Replace("args", "");
                string[] argArg = newArgLine.Split(',');

                foreach (var line in argArg)
                {
                    SplitArgs(line);
                }
            }
        }


        private static void SplitArgs(string line)
        {
            string[] arg = line.Split('=');
            string key = arg[0];
            string value = arg[1];

            if (key == "locationPathName")
            {
                locationPathName = arg[1];
            }
            else if (key == "buildTarget")
            {
                buildTarget = (BuildTarget)Enum.Parse(typeof(BuildTarget), value);
            }
            else if (key == "targetGroup")
            {
                targetGroup = (BuildTargetGroup)Enum.Parse(typeof(BuildTargetGroup), value);
            }
            else if (key == "symbols")
            {
                symbols = value;
                PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, symbols);
            }
            else if (key == "deleteFile")
            {
                Directory.Delete(value);
            }
            else if (key == "copyFile")
            {
                var pathAry = value.Split(',');
                Directory.Delete(pathAry[1]);
                IOTool.CopyDirectory(pathAry[0], pathAry[1], true);
            }
        }
    }
}
#endif